<!-- Licensed under a BSD license. See license.html for license -->
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>WebGL - Multiple Objects - list optimized</title>
    <link type="text/css" href="../resources/webgl-tutorials.css" rel="stylesheet" />
</head>

<body>
    <div id="info">
        <div class="description">
            Draw multiple objects by list with optimization checks
        </div>
        <a href="https://webglfundamentals.org/webgl/lessons/zh_cn/webgl-drawing-multiple-things.html"
            target="_blank">WebGL
            绘制多个物体</a>
    </div>
    <canvas id="canvas"></canvas>
</body>
<!--
for most samples webgl-utils only provides shader compiling/linking and
canvas resizing because why clutter the examples with code that's the same in every sample.
See http://webglfundamentals.org/webgl/lessons/webgl-boilerplate.html
and http://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html
for webgl-utils, m3, m4, and webgl-lessons-ui.
-->
<script src="../resources/webgl-utils.js"></script>
<script src="../resources/m4.js"></script>
<script src="../resources/primitives.js"></script>
<script src="../resources/chroma.min.js"></script>
<!-- vertex shader -->
<script id="3d-vertex-shader" type="x-shader/x-vertex">
attribute vec4 a_position;
attribute vec4 a_color;

uniform mat4 u_matrix;

varying vec4 v_color;

void main() {
  // Multiply the position by the matrix.
  gl_Position = u_matrix * a_position;

  // Pass the color to the fragment shader.
  v_color = a_color;
}
</script>
<!-- fragment shader -->
<script id="3d-fragment-shader" type="x-shader/x-fragment">
precision mediump float;

// Passed in from the vertex shader.
varying vec4 v_color;

uniform vec4 u_colorMult;

void main() {
   gl_FragColor = v_color * u_colorMult;
}
</script>
<script>
    "use strict";

    function main() {
        // Get A WebGL context
        /** @type {HTMLCanvasElement} */
        var canvas = document.getElementById("canvas");
        var gl = canvas.getContext("webgl");
        if (!gl) {
            return;
        }

        var createFlattenedVertices = function (gl, vertices) {
            return webglUtils.createBufferInfoFromArrays(
                gl,
                primitives.makeRandomVertexColors(
                    primitives.deindexVertices(vertices),
                    {
                        vertsPerColor: 6,
                        rand: function (ndx, channel) {
                            return channel < 3 ? ((128 + Math.random() * 128) | 0) : 255;
                        }
                    })
            );
        };

        var sphereBufferInfo = createFlattenedVertices(gl, primitives.createSphereVertices(10, 12, 6));
        var cubeBufferInfo = createFlattenedVertices(gl, primitives.createCubeVertices(20));
        var coneBufferInfo = createFlattenedVertices(gl, primitives.createTruncatedConeVertices(10, 0, 20, 12, 1, true, false));

        // 将图形放在数组中以便随机抽取
        var shapes = [
            sphereBufferInfo,
            cubeBufferInfo,
            coneBufferInfo,
        ];


        // setup GLSL program
        var programInfo = webglUtils.createProgramInfo(gl, ["3d-vertex-shader", "3d-fragment-shader"]);

        function degToRad(d) {
            return d * Math.PI / 180;
        }

        function rand(min, max) {
            return Math.random() * (max - min) + min;
        }

        function emod(x, n) {
            return x >= 0 ? (x % n) : ((n - (-x % n)) % n);
        }


        var cameraAngleRadians = degToRad(0);
        var fieldOfViewRadians = degToRad(60);
        var cameraHeight = 50;

        // 创建两个对象数组，一个用于绘制，一个用于使用
        var objectsToDraw = [];
        var objects = [];

        // Make infos for each object for each object.
        var baseHue = rand(0, 360);
        // 每个物体的全局变量
        var numObjects = 200;
        for (var ii = 0; ii < numObjects; ++ii) {

            // 创建一个物体
            var object = {
                uniforms: {
                    u_colorMult: chroma.hsv(emod(baseHue + rand(0, 120), 360), rand(0.5, 1), rand(0.5, 1)).gl(),
                    u_matrix: m4.identity(),
                },
                translation: [rand(-100, 100), rand(-100, 100), rand(-150, -50)],
                xRotationSpeed: rand(0.8, 1.2),
                yRotationSpeed: rand(0.8, 1.2),
            };
            objects.push(object);
            // 添加到绘制数组中
            objectsToDraw.push({
                programInfo: programInfo,
                bufferInfo: shapes[ii % shapes.length],
                uniforms: object.uniforms,
            });
        }

        function computeMatrix(viewProjectionMatrix, translation, xRotation, yRotation) {
            var matrix = m4.translate(viewProjectionMatrix,
                translation[0],
                translation[1],
                translation[2]);
            matrix = m4.xRotate(matrix, xRotation);
            return m4.yRotate(matrix, yRotation);
        }

        requestAnimationFrame(drawScene);

        // Draw the scene.
        function drawScene(time) {
            time *= 0.0005;

            webglUtils.resizeCanvasToDisplaySize(gl.canvas);

            // Tell WebGL how to convert from clip space to pixels
            gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

            gl.enable(gl.CULL_FACE);
            gl.enable(gl.DEPTH_TEST);

            // Clear the canvas AND the depth buffer.
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

            // Compute the projection matrix
            var aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
            var projectionMatrix =
                m4.perspective(fieldOfViewRadians, aspect, 1, 2000);

            // Compute the camera's matrix using look at.
            var cameraPosition = [0, 0, 100];
            var target = [0, 0, 0];
            var up = [0, 1, 0];
            var cameraMatrix = m4.lookAt(cameraPosition, target, up);

            // Make a view matrix from the camera matrix.
            var viewMatrix = m4.inverse(cameraMatrix);

            var viewProjectionMatrix = m4.multiply(projectionMatrix, viewMatrix);

            // 计算每个物体的矩阵
            objects.forEach(function (object) {
                object.uniforms.u_matrix = computeMatrix(
                    viewProjectionMatrix,
                    object.translation,
                    object.xRotationSpeed * time,
                    object.yRotationSpeed * time);
            });

            // ------ Draw the objects --------

            var lastUsedProgramInfo = null;
            var lastUsedBufferInfo = null;

            objectsToDraw.forEach(function (object) {
                var programInfo = object.programInfo;
                var bufferInfo = object.bufferInfo;
                var bindBuffers = false;

                if (programInfo !== lastUsedProgramInfo) {
                    lastUsedProgramInfo = programInfo;
                    gl.useProgram(programInfo.program);

                    // 更换程序后要重新绑定缓冲，因为只需要绑定程序要用的缓冲。
                    // 如果两个程序使用相同的bufferInfo但是第一个只用位置数据，
                    // 当我们从第一个程序切换到第二个时，有些属性就不存在。
                    bindBuffers = true;
                }

                // 设置所需的属性
                if (bindBuffers || bufferInfo !== lastUsedBufferInfo) {
                    lastUsedBufferInfo = bufferInfo;
                    webglUtils.setBuffersAndAttributes(gl, programInfo, bufferInfo);
                }

                // 设置全局变量
                webglUtils.setUniforms(programInfo, object.uniforms);

                // 绘制
                gl.drawArrays(gl.TRIANGLES, 0, bufferInfo.numElements);
            });

            requestAnimationFrame(drawScene);
        }
    }

    main();
</script>

</html>